<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="在js中字符截取函数有常用的三个slice()、substring()、substr()了，下面我来给大家介绍slice()、substring()、substr()函数在字符截取时的一些用法与区别吧。 取字符串的三个函数:slice(start,[end])、substring(start,[end])和substr(start,[length]) 相关属性： slice()第一个参数代表开始位">
<meta property="og:type" content="article">
<meta property="og:title" content="js字符串截取函数">
<meta property="og:url" content="http://yoursite.com/2018/10/26/Js字符串截取函数slice()、substring()、substr()/index.html">
<meta property="og:site_name" content="From&#39;s blog">
<meta property="og:description" content="在js中字符截取函数有常用的三个slice()、substring()、substr()了，下面我来给大家介绍slice()、substring()、substr()函数在字符截取时的一些用法与区别吧。 取字符串的三个函数:slice(start,[end])、substring(start,[end])和substr(start,[length]) 相关属性： slice()第一个参数代表开始位">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-10-26T02:30:40.051Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js字符串截取函数">
<meta name="twitter:description" content="在js中字符截取函数有常用的三个slice()、substring()、substr()了，下面我来给大家介绍slice()、substring()、substr()函数在字符截取时的一些用法与区别吧。 取字符串的三个函数:slice(start,[end])、substring(start,[end])和substr(start,[length]) 相关属性： slice()第一个参数代表开始位">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/26/Js字符串截取函数slice()、substring()、substr()/"/>





  <title>js字符串截取函数 | From's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">From's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/26/Js字符串截取函数slice()、substring()、substr()/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Wang hang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="From's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js字符串截取函数</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-10-26T10:29:10+08:00">
                2018-10-26
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在js中字符截取函数有常用的三个slice()、substring()、substr()了，下面我来给大家介绍slice()、substring()、substr()函数在字符截取时的一些用法与区别吧。</p>
<p>取字符串的三个函数:slice(start,[end])、substring(start,[end])和substr(start,[length])</p>
<p>相关属性：</p>
<p><code>slice()</code><br>第一个参数代表开始位置,第二个参数代表结束位置的下一个位置,截取出来的字符串的长度为第二个参数与第一个参数之间的差;若参数值为负数,则将该值加上字符串长度后转为正值;若第一个参数等于大于第二个参数,则返回空字符串.</p>
<p><code>substring()</code><br>第一个参数代表开始位置,第二个参数代表结束位置的下一个位置;若参数值为负数,则将该值转为0;两个参数中,取较小值作为开始位置,截取出来的字符串的长度为较大值与较小值之间的差.</p>
<p><code>substr()</code><br>第一个参数代表开始位置,第二个参数代表截取的长度</p>
<p>PS：字符串都从0开始计起</p>
<p>例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&lt;script type=&quot;text/[javascript](http://www.111cn.net/js_a/js.html)&quot;&gt;</span><br><span class="line">      var stmp = &quot;rcinn.cn&quot;;</span><br><span class="line">      //使用一个参数</span><br><span class="line">      alert(stmp.slice(3));//从第4个字符开始,截取到最后个字符;返回&quot;nn.cn&quot;</span><br><span class="line">      alert(stmp.substring(3));//从第4个字符开始,截取到最后个字符;返回&quot;nn.cn&quot;</span><br><span class="line"></span><br><span class="line">      //使用两个参数</span><br><span class="line">      alert(stmp.slice(1,5))//从第2个字符开始，到第5个字符；返回&quot;cinn&quot;</span><br><span class="line">      alert(stmp.substring(1,5));//从第2个字符开始，到第5个字符；返回&quot;cinn&quot;</span><br><span class="line"></span><br><span class="line">      //如果只用一个参数并且为0的话，那么返回整个参数</span><br><span class="line">      alert(stmp.slice(0));//返回整个字符串</span><br><span class="line">      alert(stmp.substring(0));//返回整个字符串</span><br><span class="line"></span><br><span class="line">      //返回第一个字符</span><br><span class="line"></span><br><span class="line">      alert(stmp.slice(0,1));//返回&quot;r&quot;</span><br><span class="line">      alert(stmp.substring(0,1));//返回&quot;r&quot;</span><br><span class="line"></span><br><span class="line">      //在上面的例子中我们可以看出slice()和substring()的用法是相同的</span><br><span class="line">      //返回的值也是一样的，但当参数为负数时，他们的返回值却不一样，看下面的例子</span><br><span class="line">      alert(stmp.slice(2,-5));//返回&quot;i&quot;</span><br><span class="line">      alert(stmp.substring(2,-5));//返回&quot;rc&quot;</span><br><span class="line">      //从上面两个例子可以看出slice(2,-5)实际上是slice(2,3)</span><br><span class="line">      //负5加上字符串长度8转换成正3(若第一位数字等于或大于第二位数字,则返回空字符串);</span><br><span class="line">      //而substring(2,-5)实际上是substring(2,0),负数转换为0,substring总是把较小的数作为起始位置。</span><br><span class="line"></span><br><span class="line">      alert(stmp.substring(1,5))//从第2个字符开始，到第5个字符；返回&quot;cinn&quot;</span><br><span class="line">      alert(stmp.substr(1,5));//从第2个字符开始，截取5个字符；返回&quot;cinn.&quot;</span><br><span class="line"></span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure></p>
<p><strong>substr 和 substring方法的区别</strong><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">&lt;script type=&quot;text/javascript&quot;&gt; </span><br><span class="line">var str = &quot;0123456789&quot;;// </span><br><span class="line">alert(str.substring(0));//------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(5));//------------&quot;56789&quot; </span><br><span class="line">alert(str.substring(10));//-----------&quot;&quot; </span><br><span class="line">alert(str.substring(12));//-----------&quot;&quot; </span><br><span class="line">alert(str.substring(-5));//-----------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(-10));//----------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(-12));//----------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(0,5));//----------&quot;01234&quot; </span><br><span class="line">alert(str.substring(0,10));//---------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(0,12));//---------&quot;0123456789&quot; </span><br><span class="line">alert(str.substring(2,0));//----------&quot;01&quot; </span><br><span class="line">alert(str.substring(2,2));//----------&quot;&quot; </span><br><span class="line">alert(str.substring(2,5));//----------&quot;234&quot; </span><br><span class="line">alert(str.substring(2,12));//---------&quot;23456789&quot; </span><br><span class="line">alert(str.substring(2,-2));//---------&quot;01&quot; </span><br><span class="line">alert(str.substring(-1,5));//---------&quot;01234&quot; </span><br><span class="line">alert(str.substring(-1,-5));//--------&quot;&quot; </span><br><span class="line">alert(str.substr(0));//---------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(5));//---------------&quot;56789&quot; </span><br><span class="line">alert(str.substr(10));//--------------&quot;&quot; </span><br><span class="line">alert(str.substr(12));//--------------&quot;&quot; </span><br><span class="line">alert(str.substr(-5));//--------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(-10));//-------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(-12));//-------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(0,5));//-------------&quot;01234&quot; </span><br><span class="line">alert(str.substr(0,10));//------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(0,12));//------------&quot;0123456789&quot; </span><br><span class="line">alert(str.substr(2,0));//-------------&quot;&quot; </span><br><span class="line">alert(str.substr(2,2));//-------------&quot;23&quot; </span><br><span class="line">alert(str.substr(2,5));//-------------&quot;23456&quot; </span><br><span class="line">alert(str.substr(2,12));//------------&quot;23456789&quot; </span><br><span class="line">alert(str.substr(2,-2));//------------&quot;&quot; </span><br><span class="line">alert(str.substr(-1,5));//------------&quot;01234&quot; </span><br><span class="line">alert(str.substr(-1,-5));//-----------&quot;&quot; </span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure></p>
<p>函数：split()<br>功能：使用一个指定的分隔符把一个字符串分割存储到数组<br>例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">str=”jpg|bmp|gif|ico|png”;</span><br><span class="line">arr=theString.split(”|”);</span><br><span class="line">//arr是一个包含字符值”jpg”、”bmp”、”gif”、”ico”和”png”的数组</span><br></pre></td></tr></table></figure></p>
<p>函数：John()<br>功能：使用您选择的分隔符将一个数组合并为一个字符串<br>例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">var delimitedString=myArray.join(delimiter);</span><br><span class="line">var myList=new Array(”jpg”,”bmp”,”gif”,”ico”,”png”);</span><br><span class="line">var portableList=myList.join(”|”);</span><br><span class="line">//结果是jpg|bmp|gif|ico|png</span><br></pre></td></tr></table></figure></p>
<p> 函数：indexOf()<br>功能：返回字符串中匹配子串的第一个字符的下标<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">var myString=”JavaScript”;</span><br><span class="line">var w=myString.indexOf(”v”);w will be 2</span><br><span class="line">var x=myString.indexOf(”S”);x will be 4</span><br><span class="line">var y=myString.indexOf(”Script”);y will also be 4</span><br><span class="line"></span><br><span class="line">var z=myString.indexOf(”key”);z will be -1</span><br></pre></td></tr></table></figure></p>
<p>在网上看到另一种非常简单的方法，代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">　　function func(s, n) &#123;</span><br><span class="line">　　　　return s.replace(/([^x00-xff])/g, “$1a”).slice(0, n).replace(/([^x00-xff])a/g, “$1″);</span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个方法非常巧妙，而且基本上是正确的。说“基本上”是因为它在取“123汉字测试”左边长度为 6 的子串时，它返回的是“123汉字”，而不是“123汉”。当然，这也并不一定就是问题，某些情况下需求可能就是这样。这个方法还可以再改进一下，如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function func(s, n) &#123;</span><br><span class="line">　　　　return s.slice(0, n).replace(/([^x00-xff])/g, “$1a”).slice(0, n).replace(/([^x00-xff])a/g, “$1″);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/13/class类的使用/" rel="next" title="class类的使用">
                <i class="fa fa-chevron-left"></i> class类的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Wang hang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">52</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">tags</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Wang hang</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
